package com.lsh.mq;

import com.lsh.service.EmailService;
import org.apache.activemq.command.ActiveMQMapMessage;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import java.util.Map;

/**
 * 邮箱注册消费者
 * 发送激活邮件至注册邮箱账号
 * @author Administrator
 * @date 2019/11/08 16:19
 */
public class EmailRegisterConsumer implements MessageListener {

    private Logger log = Logger.getLogger(this.getClass());

    @Autowired
    EmailService emailService;

    @Autowired
    TemplateEngine templateEngine;


    @Override
    public void onMessage(Message message) {
        String toEmail = null;
        try {
            Map<String, Object> contentMap = ((ActiveMQMapMessage) message).getContentMap();
            // 发送邮件
            toEmail = contentMap.get("email").toString();
            Context context = new Context();
            context.setVariable("username", contentMap.get("username"));
            context.setVariable("authCode", contentMap.get("authCode"));

            String content = templateEngine.process("mailTemplate.html", context);
            emailService.sendHtmlMail(toEmail, "欢迎注册MyBlog", content);
            log.info("已成功发送邮件至" + toEmail);
        } catch (JMSException e) {
            e.printStackTrace();
            log.error("邮件发送失败：" + toEmail);
        }
    }
}
